define([
   'models/map/mapManager',
   'views/map/controls/L.Control.Export',
   'controllers/common/showModal',
   'text!templates/map/controls/exportControl.html',
   'text!templates/map/controls/importControl.html',
], function (ModelMap, _Export, ModalController, HTMLTemplate, HTMLImportTemplate) {

    var view = Backbone.View.extend({
        el: $("#main-content"),
        layer: undefined,
        render: function (map, layer) {
            this.layer = layer;

            var that = this;

            var exportControl = L.control.export({
                position: 'topright',
                callbackExport: function () {
                    that.exportMap();
                },
                callbackImport: function () {
                    that.showPopup();
                }
            });
            map.addControl(exportControl);

        },
        exportMap: function () {

            var that = this;

            var template = Handlebars.compile(HTMLTemplate);
            var html = template();

            (new ModalController()).show(
                  {
                      title: translate('_exportMap'),
                      html: html,
                      modalClass: "addMapLayer",
                      buttons: [
                          { "title": translate("_close"), "css": "primary", "code": "ok" },
                      ],
                      backdrop: "static",
                      onLoad: function ($modal) {
                          //postRender($modal);
                          $modal.find("select[name='fileType']").on("change", function () {
                              $modal.find(".result-link").hide();
                          });

                          $modal.find("button[data-rel='export_map']").on("click", function () {
                              that.performExport($modal.find("select[name='fileType']").val(), $modal);
                          });
                      }
                  });

        },
        performExport: function (format, $modal) {
            // TO DO: hacer andar esto..
            //opciones: 1. subir el archivo a una url y brindar el link
            // 2. Armar el archivo y descargarlo con el gestor del browser

            var that = this;
            var get_blob = function () {
                return Blob;
            }
            var BB = get_blob();

            switch (format.toLowerCase()) {
                case "kml":
                    $("#projectMapSidebar").trigger("getGeoAttributes", [function (geoAttr) {
                        var kml = that.parseLayer(geoAttr);

                        saveAs(
                          new BB(
                              [kml]
                              //[text.value || text.placeholder]
                            , { type: "text/plain;charset=" + document.characterSet }
                        )
                        , ("MapProject_KML_" + (new Date).toDateString() + ".kml")
                        );
                    }]);
                    break;
                case "geojson":
                    var strGeoJson = JSON.stringify(this.layer.toGeoJSON());
                    //var url = __baseUrl + "Default.aspx?source=" + geoJson + "&type=local&persist=1&f=" + format;
                    //$modal.find(".result-link").show();
                    //$modal.find(".result-link a").attr("href", url).html(url);
                    
                    saveAs(
                          new BB(
                              [strGeoJson]
                              //[text.value || text.placeholder]
                            , { type: "text/plain;charset=" + document.characterSet }
                        )
                        , ("MapProject_GeoJSON_" + (new Date).toDateString() + ".json")
                    );

                    break;
            }


            //$("#projectMapSidebar").trigger("getGeoAttributes", [function (geoAttr) {

            //    var kml = that.parseLayer(geoAttr);
            //    var modelMap = new ModelMap();
            //    modelMap.uploadKML(kml, function (data) {
            //        var url = __geoConvertBaseUrl + "Default.aspx?source=" + data + "&type=local&persist=1&f=" + format;
            //        $modal.find(".result-link").show();
            //        $modal.find(".result-link a").attr("href", url).html(url);


            //    });
            //}]);

        },
        // iterate on layer and generate KML
        parseLayer: function (extraAttributes) {

            var that = this;
            var kml = '<?xml version="1.0" encoding="utf-8" ?><kml xmlns="http://www.opengis.net/kml/2.2"><Document>';

            var folderNodes = '<Folder><name>Nodes</name>';
            var folderLinks = '<Folder><name>Links</name>';
            var mainSchema = {};

            this.layer.eachLayer(function (layer) {

                var extraAtts = undefined;
                var attKey = "";
                if (layer instanceof L.Marker)
                    attKey = "node" + layer.options.entityId;
                else
                    attKey = "link" + layer.options.entityId;

                if (extraAttributes[attKey])
                    extraAtts = extraAttributes[attKey];

                var placemark = "<Placemark>";
                placemark += "<name>" + layer.options.title + "</name>";


                if ((layer.options.attributes && layer.options.attributes.length > 0) || extraAtts) {
                    placemark += '<ExtendedData><SchemaData schemaUrl="#mainSchema">'

                    if (extraAtts) {
                        $.each(extraAtts, function (ii, att) {
                            placemark += '<SimpleData name="' + escapeSingleQuote(att.Key) + '"><![CDATA[' + escapeSingleQuote(att.Value) + ']]></SimpleData>';
                            mainSchema[att.Key] = "string";
                        });
                    }
                    if (layer.options.attributes) {
                        $.each(layer.options.attributes, function (ii, att) {
                            var found = false;
                            if (extraAtts) {
                                for (var nn = 0; nn < extraAtts.length; nn++) {
                                    if (extraAtts[nn].Key.toLowerCase() == att.key.toLowerCase()) {
                                        found = true;
                                        break;
                                    }
                                }
                            }
                            if (!found) {
                                placemark += '<SimpleData name="' + escapeSingleQuote(att.key) + '"><![CDATA[' + escapeSingleQuote(att.value) + ']]></SimpleData>';
                                mainSchema[att.key] = att.type;
                            }

                        });
                    }

                    placemark += '</SchemaData></ExtendedData>'
                }



                if (layer instanceof L.Marker) {
                    placemark += "<Point><coordinates>";
                    placemark += layer.getLatLng().lng + "," + layer.getLatLng().lat + ",0";
                    placemark += "</coordinates></Point>";
                    placemark += "</Placemark>";
                    folderNodes += placemark;

                }
                else {
                    var alpha = parseInt(layer.options.opacity * 255).toString(16);
                    if (alpha.length == 1)
                        alpha = "0" + alpha;
                    var color = "0000ff";
                    if (layer.options.color && layer.options.color.length == 7) {
                        var aux = layer.options.color.substr(1);
                        color = aux.substr(4, 2) + aux.substr(2, 2) + aux.substr(0, 2);
                    }
                    // the kml color is aabbggrr (jojo)
                    placemark += "<Style><LineStyle><color>" + alpha + color + "</color></LineStyle></Style>";
                    placemark += "<LineString><coordinates>";
                    $.each(layer.getLatLngs(), function (ii, latlng) {
                        placemark += latlng.lng + "," + latlng.lat + ",0 ";
                    });
                    placemark += "</coordinates></LineString>";
                    placemark += "</Placemark>";
                    folderLinks += placemark;

                }
            });
            if (folderNodes != '<Folder><name>Nodes</name>') {
                folderNodes += "</Folder>";
                kml += folderNodes;
            }
            if (folderLinks != '<Folder><name>Links</name>') {
                folderLinks += "</Folder>";
                kml += folderLinks;
            }


            //Schema
            if (mainSchema) {
                kml += '<Schema id="mainSchema">';
                for (var key in mainSchema) {
                    kml += '<SimpleField name="' + key + '" type="' + mainSchema[key] + '"></SimpleField>';
                }
                kml += '</Schema>';
            }


            kml += "</Document></kml>";

            return kml;

        },
        showPopup: function () {

            var template = Handlebars.compile(HTMLImportTemplate);
            var html = template();
            var that = this;


            (new ModalController()).show(
          {
              title: translate('_addMapLayer'),
              html: html,
              modalClass: "addMapLayer",
              buttons: [
                  { "title": "OK", "css": "primary", "code": "ok" },
                  { "title": translate("cancel"), "code": "cancel" }
              ],
              callback: function (code, $modal) {
                  if (code == "ok") {

                      var form = $modal.find("form");
                      form.submit(); // throw validate form
                      if ($(form).validate().errorList.length > 0) {
                          return false
                      }
                      else {
                          return that.addLayer($modal);
                      }
                  }

              },
              onLoad: function ($modal) {
                  postRender($modal);

                  // tabs
                  $modal.find(".nav-tabs li a").on("click", function () {
                      $modal.find(".nav-tabs li").removeClass("active");
                      $(this).parent().addClass("active");
                      $modal.find(".tab-pane").removeClass("active");
                      $modal.find($(this).attr("data-rel")).addClass("active");
                  });



                  //library table 
                  //var oTable = $modal.find("#addMapLayer_FromLibrary table").dataTable({
                  //    aoColumns: [
                  //                    { sWidth: "80%", mData: "name" },
                  //                    {
                  //                        sWidth: "20%", mData: "createdDate", mRender: function (data, type, full) {
                  //                            return formatDate(data);
                  //                        }
                  //                    }
                  //    ],
                  //    sPaginationType: "full_numbers",
                  //    sDom: "ft",
                  //    sScrollY: "200px",
                  //    bInfo: false,
                  //    bLengthChange: false,
                  //    bPaginate: false,
                  //    fnCreatedRow: function (nRow, aData, iDataIndex) {
                  //        $(nRow).attr('data-rel', aData.idLayerLibrary);
                  //    }
                  //});
                  //get layerlibrarys
                  //var mapModel = new ModelMap();
                  //mapModel.listLayerLibrary(function (data) {
                  //    oTable.fnAddData(data);
                  //})
                  //end table


                  $modal.find("#addMapLayer_FromLibrary table tbody").on('click', 'tr', function () {
                      $(this).closest("table").find("tr.selected").removeClass('selected');
                      $(this).addClass('selected');
                  });



                  $modal.find("select[name='layerType']").change(function () {
                      var type = $(this).val();
                      if (type == "arcgisserver") {
                          $modal.find(".layertype_file").hide();
                          $modal.find(".layertype_url").show();
                      }
                      else {
                          $modal.find(".layertype_file").show();
                          $modal.find(".layertype_url").hide();
                      }
                  });

                  that.formValidate($modal);
                  that.configureUploader($modal);


              }
          });

        },
        addLayer: function ($modal) {

            var res = false;
            /*
            if ($modal.find(".nav-tabs li a[data-rel='#addMapLayer_FromLibrary']").parent().hasClass("active")) {

                if ($modal.find("#addMapLayer_FromLibrary table tbody tr.selected").length > 0) {
                    res = true;
                    var mapModel = new ModelMap();
                    var key = $modal.find("#addMapLayer_FromLibrary table tbody tr.selected").attr("data-rel");

                    var layerName = $modal.find("#addMapLayer_FromLibrary table tbody tr.selected td").first().html();
                    var url = __apiURL + "FPLayerLibrary/GetContent/" + key;

                    $("#projectmap").trigger("addKMLLayer", [layerName, url, true]);

                }
            }
            else {

                //var url = __geoConvertUrl;
                var layerName = $modal.find("input[name='layerName']").val();

                if ($modal.find("select[name='layerType']").val() == "arcgisserver") {
                    url = url.replace("##source##", $modal.find("input[name='layerUrl']").val());
                    url = url.replace("##type##", "external");
                    res = true;

                    // add layer to map
                    $("#projectmap").trigger("addKMLLayer", [layerName, url]);

                }
                else {
                    // perform upload
                    if (this.uploader && this.uploader.files.length > 0) {
                        this.uploader.start();
                        $modal.find("button[data-code='ok']").attr("disable", "disable");
                    }
                }
            }*/
            if (this.uploader && this.uploader.files.length > 0) {
                this.uploader.start();
                $modal.find("button[data-code='ok']").attr("disable", "disable");
                res = true;
            }
            return res;
        },
        formValidate: function ($modal) {
            var tradeCompTotal = $modal.find("form .tradeCompTotal");

            $modal.find("form").validate({
                rules: {
                    layerName: {
                        required: function () { return ($modal.find(".nav-tabs li a[data-rel='#addMapLayer_NewFile']").parent().hasClass("active")) },
                    },
                    layerUrl: {
                        required: function () {
                            return ($modal.find(".nav-tabs li a[data-rel='#addMapLayer_NewFile']").parent().hasClass("active") &&
                                $modal.find("select[name='layerType']").val() == "arcgisserver")
                        },

                    },
                    layerFile: {
                        required: function () {
                            return ($modal.find(".nav-tabs li a[data-rel='#addMapLayer_NewFile']").parent().hasClass("active") &&
                                $modal.find("select[name='layerType']").val() != "arcgisserver")
                        },
                    },
                    layerLibrary: {
                        required: function () {
                            return ($modal.find(".nav-tabs li a[data-rel='#addMapLayer_FromLibrary']").parent().hasClass("active") &&
                                                    $modal.find(".dataTables_scrollBody table tr.selected").length == 0)
                        },
                    },
                },
                submitHandler: function (form) {
                    return false;
                }
            });

        },
        configureUploader: function ($modal) {



            this.uploader = new plupload.Uploader({
                runtimes: 'html5,browserplus,html4',
                browse_button: $modal.find("a.addLayerFile").get(0),
                url: __geoConvertBaseUrl + "uploader.aspx",

                filters: {
                    max_file_size: '200mb',
                    mime_types: [
                        { title: "Zip files", extensions: "zip" },
                        { title: "Arcgis", extensions: "e00" },
                        { title: "KML", extensions: "kml" },
                        { title: "Geojson", extensions: "txt,json" }
                    ]
                },
                multi_selection: false,

                init: {
                    PostInit: function () {
                        $modal.find("div.filelist").html("");
                    },

                    FilesAdded: function (up, files) {
                        plupload.each(files, function (file) {
                            $modal.find("div.filelist").append('<div id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ') <b></b></div>');
                            if ($modal.find("input[name='layerName']").val() == "") {
                                var fname = file.name.substr(0, file.name.lastIndexOf('.')) || file.name;
                                $modal.find("input[name='layerName']").val(fname);
                            }
                        });

                        up.disableBrowse(true);
                    },


                    UploadProgress: function (up, file) {
                        $modal.find("#" + file.id).find("b").html('<span>' + file.percent + "%</span>");
                    },
                    FileUploaded: function (upldr, file, object) {


                        if (object.response && object.response.indexOf("ERROR:") == 0) {
                            alert(object.response);
                            return;
                        }

                        var localFile = object.response;
                        // trigger load kml event
                        var layerName = $modal.find("input[name='layerName']").val();
                        var url = __geoConvertUrl;
                        url = url.replace("##source##", localFile);
                        url = url.replace("##type##", "local");
                        $("#projectmap").trigger("addKMLLayer", [layerName, url]);

                        // close popup
                        $("#main-modal").off('shown');
                        $("#main-modal").modal("hide");
                    },

                    Error: function (up, err) {
                        alert("\nError #" + err.code + ": " + err.message);
                    }
                }
            });

            this.uploader.init();

        },



    });
    return view;
});
